%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Module summary
%%
%% Library functions for 
%% mysql connection
%%
%%%%%%%%%%%%%%%%%%%%%%%

-module(mysql_lib).

-compile(export_all).

-define(DATABASE, "kandidat").
-define(TABLE, "apa").
-define(KEY, "table_key").
-define(VALUE, "table_value").
-define(PORT, 25000).
-define(USERNAME, "root").
-define(PASSWORD, "root").
-define(HOST, "localhost").


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
%%%
%%% Start and stop
%%%
%%%
%%% User :: string()
%%% Port :: int()
%%% User :: string()
%%% Password :: string()
%%%

start() ->
    start(?HOST, ?PORT, ?USERNAME, ?PASSWORD).

start(Host) ->    
    start(Host, ?PORT, ?USERNAME, ?PASSWORD).

start(User, Password) ->
    start(?HOST, ?PORT, User, Password).

start(Host, Port, User, Password) ->
    case is_started() of
        false ->
            crypto:start(),
            {ok, Pid} = mysql_conn:start(Host, Port, User, Password,
                                          ?DATABASE, undefined),
            register(?MODULE, spawn(?MODULE, loop, [Pid]));
        true -> 
            {error,already_started}
    end.

stop() ->
    case is_started() of
        true  ->
            ?MODULE ! {stop};
        false ->
            {error,not_started}
    end.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
%%%
%%% Query functions
%%%
put(Key, Value) ->
    Query = "INSERT INTO " ++ ?TABLE ++ " (" ++ 
             ?KEY ++ "," ++ ?VALUE ++ ") VALUES ('" ++
             Key ++ "','" ++ Value ++ "')",
    ?MODULE ! {fetch, Query,self()},
    receive
        {reply, Reply} -> Reply
    end.

% Insert list of type [{Key,Value}]
put_list(Values) ->
    [mysql_lib:put(Key,Value) || {Key,Value} <- Values].


 
get(Key) ->
    Query = "SELECT * FROM " ++ ?TABLE ++ " WHERE " ++ 
                          ?KEY ++ " = '" ++ Key ++ "'",
    ?MODULE ! {fetch, Query,self()},
    receive
        {reply, Reply} -> Reply
    end.

% Get list of type [{Key,Value}]
get_list(Values) ->
    [mysql_lib:get(Key) || {Key,_} <- Values].



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
%%%
%%% Main Loop
%%%
loop(Pid) ->
    receive
        {fetch, Query,Pid2} -> 
                          Result = mysql_conn:fetch(Pid, Query, self()),
                          Pid2 ! {reply,Result},
                          %io:format("Executed: ~p~n", [Query]),
                          %io:format("Received: ~p~n", [Result]),
                          loop(Pid);
        {stop} -> mysql_conn:stop(Pid),
                  ok
    end.


is_started() ->
    case whereis(?MODULE) of
        undefined -> false;
        _         -> true
    end.
